#!/bin/bash
# translux - Translate labels using keys as variables
# Jon Peeters - June 2011

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

labels_prefix="resources/labels_"

_tr_all() {
	labels_file="${labels_prefix}$lng"
	if [[ ${#labels_sections[@]} -eq 0 ]]; then
		labels_sections[0]="$labels"
	fi
	for labels in ${labels_sections[@]}; do
		_tr_section
	done
}

_tr_section() {
	if [[ -z "$lng" ]]; then 
		lng="en"
		labels_file="${labels_prefix}$lng"
	fi
	if [[ -f "$labels_file" ]]; then
		sectionfound=1
		while read line; do
			if [[ "$line" =~ ^# ]]; then
				sectiontmp="${line#\#}"
				if [[ "$sectiontmp" == "$label" ]]; then
					sectionfound=0
					continue
				fi
			elif [[ "$line" =~ ^" "*$ ]]; then
				if [[ $sectionfound -eq 0 ]]; then
					break
				else
					continue
				fi
			fi
			var="${line%=*}"
			val="${line#*=}"
			eval $var='$val'
		done < "$labels_file"
	else
		zenity --error --text="Error : cannot translate labels (section:$labels).\nFile not found : $labels_file"
	fi
}
 
translate_labels () {
	newlng="$1"
	if [[ -n "$newlng" ]]; then
		if [[ "$newlng" != "$lng" ]]; then
			lng="$newlng"
			_tr_all
		else
			_tr_section
		fi
	else
		_tr_section
	fi
}
